package org.example.greenhouse.service.impl;

import org.example.greenhouse.dao.CameraDao;
import org.example.greenhouse.entity.Camera;
import org.example.greenhouse.entity.Device;
import org.example.greenhouse.result.Result;
import org.example.greenhouse.service.CameraService;
import org.example.greenhouse.service.DeviceService;
import org.example.greenhouse.utils.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class CameraServiceImpl implements CameraService {
    @Autowired
    private CameraDao cameraDao;
    @Autowired
    private DeviceService deviceService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${camera.url}")
    private String cameraUrl;
    @Value("${cameraPhoto.url}")
    private String cameraPhotoUrl;

    
    @Override
    public Result updataCameraData() {
        try {
            // 1. 获取摄像头设备信息
            List<Device> cameraDevices = deviceService.getCameraDevices();
            if (cameraDevices.isEmpty()) {
                throw new RuntimeException("未找到摄像头设备");
            }
            //提取唯一的监控对象
            Device cameraDevice = cameraDevices.get(0); // 直接通过索引获取第一个设备
            int deviceId = cameraDevice.getDeviceId(); // 获取设备 ID
            String cameraSerial = cameraDevice.getSerialNumber(); // 获取设备序列号
            //获取 Token
            String accessToken = fetchAccessToken();
            //获取最新的监控图片的 URL
            String imageUrl = fetchImageUrl(cameraSerial, accessToken);
            //将图片 URL 转换为 Base64 编码
            String base64Image = ImageUtils.getImageStrFromUrl(imageUrl);
            //保存监控数据
            Camera camera = new Camera();
            camera.setDeviceId(deviceId);
            camera.setImg(base64Image);
            camera.setCreatedTime(new Date());
            cameraDao.save(camera);

            return Result.success("最新的监控图片保存成功");
        } catch (Exception e) {
            return Result.error("获取监控图片失败：" + e.getMessage());
        }
    }

    @Override
    public Result getAllCameraData() {
        try {
            List<Camera> cameras = cameraDao.findAll();
            return Result.success(cameras);
        } catch (Exception e) {
            return Result.error("获取监控数据失败：" + e.getMessage());
        }
    }

    @Override
    public Result getAccessToken() {
        try {
            String accessToken = fetchAccessToken(); // 调用已有的获取 Token 方法
            return Result.success(accessToken); // 返回 Token
        } catch (Exception e) {
            return Result.error("获取 Token 失败：" + e.getMessage());
        }
    }

    @Override
    public Result getCameraDevices() {
        try {
            List<Device> cameraDevices = deviceService.getCameraDevices();
            if (cameraDevices.isEmpty()) {
                return Result.error("未找到监控设备");
            }
            Device firstCameraDevice = cameraDevices.get(0);
            return Result.success(firstCameraDevice, "监控设备数据获取成功");
        } catch (Exception e) {
            return Result.error("获取监控设备数据失败：" + e.getMessage());
        }
    }

    // 获取token
    private String fetchAccessToken() {
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("accountId", "1ca7f0ab24ba41b291346347ec30140e");

        Map<String, Object> response = restTemplate.postForObject(cameraUrl, requestBody, Map.class);
        if (response != null && response.containsKey("data")) {
            Map<String, Object> data = (Map<String, Object>) response.get("data");
            return (String) data.get("accessToken");
        }
        throw new RuntimeException("获取 Token 失败");
    }
    //获取照片
    private String fetchImageUrl(String cameraSerial, String accessToken) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 设置请求体
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("accessToken", accessToken);
        requestBody.add("deviceSerial", cameraSerial);
        requestBody.add("channelNo", "1");
        requestBody.add("quality", "4");
        // HttpEntity
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody, headers);
        //发送 POST 请求
        Map<String, Object> response = restTemplate.postForObject(cameraPhotoUrl, request, Map.class);
        // 处理响应
        if (response != null && response.containsKey("data")) {
            Map<String, Object> data = (Map<String, Object>) response.get("data");
            return (String) data.get("picUrl");
        }
        throw new RuntimeException("抓拍图片失败");
    }

}